﻿using Microsoft.Phone.Controls;
using AccountHelper.Common;
using System;
using System.Collections.Generic;
using System.Windows.Navigation;
using MvvmLight.Messaging;
using AccountHelper.UserControls.Turnstile;
using System.Windows.Controls;
using System.Windows;
using AccountHelper.Model;
using Coding4Fun.Phone.Controls;
using Microsoft.Xna.Framework;

namespace AccountHelper.View
{
    /// <summary>
    /// Account Helper Main View 
    /// </summary>
    public partial class MainView : PhoneApplicationPage
    {
        public MainView()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainView_Loaded);
        }

        void MainView_Loaded(object sender, RoutedEventArgs e)
        {
            InitUser();
        }

        #region Init User
        private void InitUser()
        {
            if (UserInfo.userInfo!=null)
            {
                return;   
            }
            UserInfo.userInfo = PersistHelper.LoadSetttingFromStorage<User>("userInfo");
            if (null == UserInfo.userInfo)
            {
                InputPrompt ip = new InputPrompt
                {

                    Title = "亲～～",
                    Message = "哎呦，您还没账户，创建一个吧",
                };
                ip.Completed += (s, o) =>
                {
                    if (o.PopUpResult == PopUpResult.Ok)
                    {
                        User u = new User
                        {
                            UserName = o.Result,
                            CurCharge = 0,
                            CurCost = 0,
                            CurYearMonth = DateHelper.GetYearMonth(DateTime.Now),
                            ProfileImageUri = new Uri("/Images/a97911.jpg", UriKind.Relative),
                        };
                        UserInfo.userInfo = u;
                        ViewModelLocator.Instance.MainVM.CurrentUser = u;
                        PersistHelper.SaveSettingToStorage("userInfo", UserInfo.userInfo);
                    }
                    else
                    {
                        //just exit the App
                        new Game().Exit();
                        return;
                    }
                };
                ip.Show();
            }
            else
            {
                ViewModelLocator.Instance.MainVM.CurrentUser = UserInfo.userInfo;
            }
        }
        #endregion

        private void TileClickEffectBehavior_ClickAnimationCompleted(object sender, EventArgs e)
        {
            tilesControl.AnimateTiles(EnterMode.Exit, YDirection.TopToBottom, ZDirection.FrontToBack, TimeSpan.FromMilliseconds(400));
        }

        private void RegisterMessenger()
        {
            /*
            * 为了ViewModel中可以进行页面的跳转，有两种方式
            * 1. 在页面的code-behind中注册Messenger，参数为Uri，然后就可以在ViewModel中发送消息进行跳转
            * 2. 编写INavigation，自己在ViewModel中实现Frame的跳转
            * http://geekswithblogs.net/lbugnion/archive/2011/01/06/navigation-in-a-wp7-application-with-mvvm-light.aspx
            **/
            Messenger.Default.Register<Uri>(this, "Navigation", (p) =>
            {
                TileClickEffectBehavior_ClickAnimationCompleted(null, null);
                this.NavigationService.Navigate(p);
            });

            //Register Messenger for changing the default item of panorama control
            Messenger.Default.Register<int>(this, "MainView_SelectedIndex", (p) =>
            {
                switch (p)
                {
                    case 0:
                        accountPanorama.DefaultItem = this.piMenu;
                        break;
                    case 1:
                        accountPanorama.DefaultItem = this.piCost;
                        break;
                    case 2:
                        accountPanorama.DefaultItem = this.piCharge;
                        break;
                    case 3:
                        accountPanorama.DefaultItem = this.piProfile;
                        break;
                    default:
                        break;
                }
            });
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            RegisterMessenger();

            if (null != ViewModelLocator.Instance.MainVM.MenuList)
            {
                if (ViewModelLocator.Instance.MainVM.IsFirstLoad)
                {
                    RunExitAnimation();
                }
                if (!ViewModelLocator.Instance.MainVM.IsFirstLoad)
                {
                    ViewModelLocator.Instance.MainVM.IsFirstLoad = true;
                }
            }
            base.OnNavigatedTo(e);
        }

        private void RunExitAnimation()
        {
            tilesControl.ItemsSource = null;
            tilesControl.Opacity = 0;
            tilesControl.ItemsSource = ViewModelLocator.Instance.MainVM.MenuList;
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                tilesControl.Opacity = 1;
                tilesControl.AnimateTiles(
                    EnterMode.Enter,
                    YDirection.BottomToTop,
                    ZDirection.BackToFront);
            });
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //unregister messenger to avoid memory leak
            Messenger.Default.Unregister<Uri>(this, "Navigation");
            Messenger.Default.Unregister<int>(this, "MainView_SelectedIndex");
            base.OnNavigatedFrom(e);
        }

        private void accountPanorama_SelectionChanged
            (object sender, SelectionChangedEventArgs e)
        {
            //bind select index to view model for loading data
            ViewModelLocator.Instance.MainVM.SelectIndex = 
                this.accountPanorama.SelectedIndex;
        }

    }
}